package com.my.house;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.IFill;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.TemplateType;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.fill.Column;
import com.my.house.common.BaseDomain;
import org.apache.ibatis.jdbc.ScriptRunner;

import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

/**
 * @author: lijia@joyame.com
 */
public class CodeGenerator {

    /**
     * TODO 生成代码记得修改下面路径
     */
    private static final String PACKAGE_NAME = "com.my.house";
    private static final String OUTPUT_DIR = System.getProperty("user.dir") + File.separator + "src/main/java";
    public static final String URL = "jdbc:mysql://127.0.0.1:3306/myhouse?useSSL=false&useUnicode=true&characterEncoding=UTF-8&allowPublicKeyRetrieval=true&socketTimeout=50000&connectTimeout=50000&autoConnect=true&rewriteBatchedStatements=true&serverTimezone=Asia/Shanghai";
    public static final String USERNAME = "root";
    public static final String PASSWORD = "a123456";
    /**
     * 推荐使用create_time,modify_time,create_by,modify_by，del_flag等作为表通用字段 逻辑删除项目默认使用0正常数据 1已删除数据
     */
    private static final List<IFill> fillList = Arrays.asList(new Column("created_by", FieldFill.INSERT), new Column("created_at", FieldFill.INSERT),
            new Column("updated_by", FieldFill.INSERT_UPDATE), new Column("updated_at", FieldFill.INSERT_UPDATE), new Column("deleted", FieldFill.INSERT));
    /**
     * 数据源配置
     */
    private static final DataSourceConfig.Builder DATA_SOURCE_CONFIG = new DataSourceConfig.Builder(URL, USERNAME, PASSWORD);

    /**
     * 执行初始化数据库脚本
     */
    public static void before() throws SQLException {
        Connection conn = DATA_SOURCE_CONFIG.build().getConn();
        InputStream inputStream = CodeGenerator.class.getResourceAsStream("/sql/init.sql");
        ScriptRunner scriptRunner = new ScriptRunner(conn);
        scriptRunner.setAutoCommit(true);
        scriptRunner.runScript(new InputStreamReader(inputStream));
        conn.close();
    }

    /**
     * 执行 run
     */
    public static void main(String[] args) {
        // 执行sql初始化
        // before();

        //逗号分隔的表名
        final String[] tables = {"fee_record"};


        FastAutoGenerator.create(DATA_SOURCE_CONFIG)
                // 全局配置 作者名
                .globalConfig(builder -> builder.author("yangll").commentDate("yyyy-MM-dd").dateType(DateType.TIME_PACK)
//                        .enableSwagger()
                        .disableOpenDir()
                        .outputDir(OUTPUT_DIR)
                )
                // 包配置 TODO 路径需要修改
                .packageConfig(builder -> builder.parent(PACKAGE_NAME).controller("controller").service("service").serviceImpl("service").entity("domain").mapper("mapper"))
                // 策略配置 表名，多个表名用,隔开
                .strategyConfig(builder -> builder.addInclude(tables)
                                .entityBuilder().disableSerialVersionUID().enableLombok().formatFileName("%s")
//                                .enableChainModel()
                                .addIgnoreColumns("deleted", "created_by", "updated_at", "created_at", "updated_by")
                                .superClass(BaseDomain.class)
                                .idType(IdType.ASSIGN_ID)  // 自增ID
                                .logicDeleteColumnName("deleted")
                                .addTableFills(fillList)
                                .controllerBuilder().enableRestStyle()
//                                .superClass(BaseController.class)
                                .mapperBuilder().enableBaseResultMap().enableBaseColumnList().disableMapperXml()
//                                没有多实现，就不创建IService接口了，如果有多实现，下面一行可以注释掉
                                .serviceBuilder().disableService().formatServiceImplFileName("%sService")
                )
                .templateConfig(builder -> builder.build()
                        // 不创建哪些类文件
//                                .disable(TemplateType.CONTROLLER)
                                .disable(TemplateType.SERVICE)
                                .disable(TemplateType.XML)
                )
//                模板引擎配置，默认 Velocity 可选模板引擎 Beetl 或 Freemarker
                .templateEngine(new FreemarkerTemplateEngine())
                .execute();

    }
}
